package GUI;

import Controladores.ControladorUsuario;
import Logico.Usuario;
import java.security.MessageDigest;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class UsuarioGUI extends javax.swing.JPanel {

    ControladorUsuario controladorUsuario;
    int cedula;
    String nombre;
    String apellido;
    String rol;
    String contrasena;
    List<Usuario> listaUsuarios;
    int indice;

    public UsuarioGUI() {
        initComponents();
        controladorUsuario = new ControladorUsuario();
        listaUsuarios = controladorUsuario.listarUsuarios();
        cedula = 0;
        indice = 0;
        inicializarTabla();
    }

    public void inicializarTabla() {
        tablaUsuarios.removeAll();
        DefaultTableModel modelo = (DefaultTableModel) tablaUsuarios.getModel();
        modelo.setRowCount(0);

        for (int i = 0; i < listaUsuarios.size(); i++) {
            String temp[] = new String[4];

            temp[0] = listaUsuarios.get(i).getCedula() + "";
            temp[1] = listaUsuarios.get(i).getNombre() + "";
            temp[2] = listaUsuarios.get(i).getApellidos() + "";
            temp[3] = listaUsuarios.get(i).getRol() + "";

            Object nuevo[] = null;
            modelo.addRow(nuevo);
            tablaUsuarios.setModel(modelo);
            for (int j = 0; j < temp.length; j++) {
                tablaUsuarios.setValueAt(temp[j], i, j);
            }
        }

        if (listaUsuarios.size() > 0) {
            indice = 0;
            actualizarFormulario();
        }

    }

    public void actualizarFormulario() {
        cedula = listaUsuarios.get(indice).getCedula();
        campoCedula.setText(cedula + "");
        nombre = listaUsuarios.get(indice).getNombre();
        campoNombre.setText(nombre);
        apellido = listaUsuarios.get(indice).getApellidos();
        campoApellido.setText(apellido);
        rol = listaUsuarios.get(indice).getRol();
        campoRol.setText(rol);
        //contrasena = listaUsuarios.get(indice).getContrasena(); esto no es necesario
        //campoContrasena.setText(contrasena);
        campoContrasena.setText("************");
    }

    public void limpiarFormulario() {
        cedula = 0;
        campoCedula.setText("");
        nombre = "";
        campoNombre.setText("");
        apellido = "";
        campoApellido.setText("");
        rol = "";
        campoRol.setText("");
        contrasena = "";
        campoContrasena.setText("");
    }

    public static String md5(String clear) throws Exception {

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] b = md.digest(clear.getBytes());
        int size = b.length;
        StringBuffer h = new StringBuffer(size);
        //algoritmo y arreglo md5
        for (int i = 0; i < size; i++) {
            int u = b[i] & 255;
            if (u < 16) {
                h.append("0" + Integer.toHexString(u));
            } else {
                h.append(Integer.toHexString(u));
            }
        }
        //clave encriptada
        return h.toString();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        campoRol = new javax.swing.JTextField();
        campoApellido = new javax.swing.JTextField();
        campoNombre = new javax.swing.JTextField();
        campoCedula = new javax.swing.JTextField();
        botonGuardar = new javax.swing.JButton();
        botonActualizar = new javax.swing.JButton();
        botonEliminar = new javax.swing.JButton();
        botonBuscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaUsuarios = new javax.swing.JTable();
        botonAnterior = new javax.swing.JButton();
        botonSiguiente = new javax.swing.JButton();
        campoContrasena = new javax.swing.JPasswordField();
        botonLimpiar = new javax.swing.JButton();

        jLabel1.setText("Cédula (*)");

        jLabel2.setText("Nombre");

        jLabel3.setText("Apellido");

        jLabel4.setText("Rol");

        jLabel5.setText("Contraseña (*)");

        botonGuardar.setText("Guardar");
        botonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonGuardarActionPerformed(evt);
            }
        });

        botonActualizar.setText("Actualizar");
        botonActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonActualizarActionPerformed(evt);
            }
        });

        botonEliminar.setText("Eliminar");
        botonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonEliminarActionPerformed(evt);
            }
        });

        botonBuscar.setText("Buscar");
        botonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonBuscarActionPerformed(evt);
            }
        });

        tablaUsuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Célula", "Nombre", "Apellido", "Rol"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tablaUsuarios);

        botonAnterior.setText("<<");
        botonAnterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAnteriorActionPerformed(evt);
            }
        });

        botonSiguiente.setText(">>");
        botonSiguiente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonSiguienteActionPerformed(evt);
            }
        });

        botonLimpiar.setText("Limpiar");
        botonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonLimpiarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(campoRol)
                            .addComponent(campoApellido)
                            .addComponent(campoNombre)
                            .addComponent(campoCedula)
                            .addComponent(campoContrasena, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(botonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(botonActualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(botonEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(botonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(botonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                        .addComponent(botonAnterior)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botonSiguiente)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(campoCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(campoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(campoApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(campoRol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(campoContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonGuardar)
                    .addComponent(botonActualizar)
                    .addComponent(botonEliminar)
                    .addComponent(botonBuscar)
                    .addComponent(botonAnterior)
                    .addComponent(botonSiguiente)
                    .addComponent(botonLimpiar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void botonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGuardarActionPerformed

        contrasena = new String(campoContrasena.getPassword());
        System.out.println("Imprimiendo contraseña: " + contrasena);
        try {
            System.out.println("Contraseña encriptada: " + md5(contrasena));
        } catch (Exception ex) {
            Logger.getLogger(UsuarioGUI.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Ha ocurrido un error con su contraseña");
        }

        if (!campoCedula.getText().equals("")
                && !campoNombre.getText().equals("")
                && !campoApellido.getText().equals("")
                && !campoRol.getText().equals("")
                && !campoContrasena.getText().equals("")) {

            cedula = Integer.parseInt(campoCedula.getText());
            nombre = campoNombre.getText();
            apellido = campoApellido.getText();
            rol = campoRol.getText();
            contrasena = new String(campoContrasena.getPassword());
            try {
                contrasena = md5(contrasena);
            } catch (Exception ex) {
                Logger.getLogger(UsuarioGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            boolean registrado = controladorUsuario.guardar(cedula, nombre, apellido, rol, contrasena);

            if (registrado) {
                JOptionPane.showMessageDialog(null, "Usuario registrado con exito");
                listaUsuarios = controladorUsuario.listarUsuarios();
                inicializarTabla();
            } else {
                JOptionPane.showMessageDialog(null, "Usuario no se pudo registrar");
            }
        } else {
            JOptionPane.showMessageDialog(null, "Ingrese los datos del formulario");
        }

    }//GEN-LAST:event_botonGuardarActionPerformed

    private void botonActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonActualizarActionPerformed

        if (campoCedula.getText().equals("") || campoContrasena.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Los campos obligatorios (*) no deben estar vacios");

        } else {
            cedula = Integer.parseInt(campoCedula.getText());
            nombre = campoNombre.getText();
            apellido = campoApellido.getText();
            rol = campoRol.getText();
            contrasena = new String(campoContrasena.getPassword());
            try {
                contrasena = md5(contrasena);
            } catch (Exception ex) {
                Logger.getLogger(UsuarioGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            boolean actualizado = controladorUsuario.modificar(cedula, nombre, apellido, rol, contrasena);

            if (actualizado) {
                JOptionPane.showMessageDialog(null, "Usuario actualizado con exito");
            } else {
                JOptionPane.showMessageDialog(null, "Usuario no pudo ser actualizado");
            }
        }
    }//GEN-LAST:event_botonActualizarActionPerformed

    private void botonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonEliminarActionPerformed

        if (cedula != 0) {
            cedula = Integer.parseInt(campoCedula.getText());
            boolean borrado = controladorUsuario.borrar(cedula);

            if (borrado) {
                JOptionPane.showMessageDialog(null, "Usuario eliminado con exito");
                limpiarFormulario();
                listaUsuarios = controladorUsuario.listarUsuarios();
                inicializarTabla();
            } else {
                JOptionPane.showMessageDialog(null, "Usuario no se pudo eliminar");
            }
        } else {
            JOptionPane.showMessageDialog(null, "Ingrese un numero de cedula");
        }
    }//GEN-LAST:event_botonEliminarActionPerformed

    private void botonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarActionPerformed

        if (cedula != 0) {
            Usuario u = controladorUsuario.buscar(cedula);
            if (u != null) {
                listaUsuarios.removeAll(listaUsuarios);
                listaUsuarios.add(u);
                inicializarTabla();
            } else {
                JOptionPane.showMessageDialog(null, "No se encontro el usuario " + cedula);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Ingrese un numero de cedula");
        }
    }//GEN-LAST:event_botonBuscarActionPerformed

    private void botonAnteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAnteriorActionPerformed

        if (indice > 0) {
            indice--;
            actualizarFormulario();
        }
    }//GEN-LAST:event_botonAnteriorActionPerformed

    private void botonSiguienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSiguienteActionPerformed

        if (indice < listaUsuarios.size() - 1) {
            indice++;
            actualizarFormulario();
        }
    }//GEN-LAST:event_botonSiguienteActionPerformed

    private void botonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonLimpiarActionPerformed

        limpiarFormulario();
    }//GEN-LAST:event_botonLimpiarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonActualizar;
    private javax.swing.JButton botonAnterior;
    private javax.swing.JButton botonBuscar;
    private javax.swing.JButton botonEliminar;
    private javax.swing.JButton botonGuardar;
    private javax.swing.JButton botonLimpiar;
    private javax.swing.JButton botonSiguiente;
    private javax.swing.JTextField campoApellido;
    private javax.swing.JTextField campoCedula;
    private javax.swing.JPasswordField campoContrasena;
    private javax.swing.JTextField campoNombre;
    private javax.swing.JTextField campoRol;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tablaUsuarios;
    // End of variables declaration//GEN-END:variables
}
